package swimv2gm.client.user;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.*;

import swimv2gm.bl.session.*;

@SuppressWarnings("serial")
public class Login extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
		doPost(request,response);
	}

	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
		UserManager man;
		try {
			man = (UserManager)InitialContext.doLookup("UserManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}

		long uid = man.login(request.getParameter("email"),request.getParameter("password"));
		if (uid < 0) {
			response.sendRedirect("/SWIMv2gm/?error=");
		}
		else {
			request.getSession().setAttribute("user",uid);
			if (man.isAdmin(uid)) {
				request.getSession().setAttribute("admin",true);
				response.sendRedirect("/SWIMv2gm/admin/console.jsp");
			}
			else {
				request.getSession().setAttribute("admin",false);
				response.sendRedirect("/SWIMv2gm/user/Profile?uid=" + uid);
			}
		}

	}
}
